package com.example.administrator.maizuofilm.moviedetails;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.maizuofilm.BaseActivity;
import com.example.administrator.maizuofilm.R;
import com.example.administrator.maizuofilm.moviedetails.bean.Comment;
import com.example.administrator.maizuofilm.moviedetails.bean.Details;
import com.example.administrator.maizuofilm.moviedetails.moviecomment.FullyLinearLayoutManager;
import com.example.administrator.maizuofilm.moviedetails.moviecomment.MoviesCommentActivity;
import com.example.administrator.maizuofilm.moviedetails.moviedetailsadapter.MovieDetailsAdapter;
import com.example.administrator.maizuofilm.moviedetails.moviedetailsadapter.MovieDetailsViewPagerAdapter;
import com.example.administrator.maizuofilm.moviedetails.moviedetailsadapter.MoviedetailsRecyAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by hansen on 2016/7/12.
 */
public class MovieDetailsActivity extends BaseActivity implements MovieDetailsContract.MovieDetailsV {
    @InjectView(R.id.moviedetails_toolbar)
    Toolbar moviedetailsToolbar;
    @InjectView(R.id.moviedatails_appbar)
    AppBarLayout moviedatailsAppbar;


    private static final float PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR = 0.9f;
    private static final float PERCENTAGE_TO_HIDE_TITLE_DETAILS = 0.3f;

    private static final int ALPHA_ANIMATIONS_DURATION = 200;
    @InjectView(R.id.moviedetails_recyclerview)
    RecyclerView moviedetailsRecyclerview;
    @InjectView(R.id.re)
    RelativeLayout re;
    private ImageView[] icons;

    @InjectView(R.id.moviedatails_movieBackground)
    ImageView moviedatailsMovieBackground;
    @InjectView(R.id.stills)
    ImageView stills;
    @InjectView(R.id.moviedatails_tvmovie)
    TextView moviedatailsTvmovie;
    @InjectView(R.id.moviedatails_tvmovieIsD)
    TextView moviedatailsTvmovieIsD;
    @InjectView(R.id.moviedatails_movieEnglish)
    TextView moviedatailsMovieEnglish;
    @InjectView(R.id.moviedatails_movieType)
    TextView moviedatailsMovieType;
    @InjectView(R.id.moviedatails_movieTime)
    TextView moviedatailsMovieTime;
    @InjectView(R.id.moviedatails_movieAddress)
    TextView moviedatailsMovieAddress;
    @InjectView(R.id.moviedtails_back)
    ImageView moviedtailsBack;
    @InjectView(R.id.moviedetails_toolbarTitle)
    TextView moviedetailsToolbarTitle;
    @InjectView(R.id.moviedatails_movieRecommend)
    TextView moviedatailsMovieRecommend;
    @InjectView(R.id.moviedatails_recyclerView)
    RecyclerView moviedatailsRecyclerView;
    @InjectView(R.id.moviedetails_grade)
    TextView moviedetailsGrade;
    @InjectView(R.id.moviedetails_play)
    ImageView moviedetailsPlay;
    @InjectView(R.id.moviedatails_still)
    ImageView moviedatailsStill;
    @InjectView(R.id.movieback)
    ImageView movieback;
    @InjectView(R.id.movieplay)
    ImageView movieplay;
    @InjectView(R.id.moviedetails_ivCommend)
    ImageView moviedetailsIvCommend;
    @InjectView(R.id.moviedetails_ivGood)
    ImageView moviedetailsIvGood;
    @InjectView(R.id.moviedetails_ivShare)
    ImageView moviedetailsIvShare;
    @InjectView(R.id.moviedetails_viewpager)
    ViewPager moviedetailsViewpager;
    @InjectView(R.id.moviedetails_articleTitle)
    TextView moviedetailsArticleTitle;
    @InjectView(R.id.moviedetails_linear)
    LinearLayout moviedetailsLinear;


    private boolean mIsTheTitleVisible = false;
    private boolean mIsTheTitleContainerVisible = true;
    private MovieDetailsContract.MovieDetailsM mModel;
    private MovieDetailsContract.MovieDetailsP mPresenter;
    private GridLayoutManager manager;
    private Details details;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moviedetails);
        ButterKnife.inject(this);

        setSupportActionBar(moviedetailsToolbar);


        //接受上个界面传过来的值
        Intent intent = getIntent();
        String filmID = intent.getStringExtra("filmID");


        mModel = new MovieDetailsModel();
        mPresenter = new MovieDetailsPresenter(mModel, this);

        // AppBar的监听
        moviedatailsAppbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int maxScroll = appBarLayout.getTotalScrollRange();
                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;

                handleToolbarTitleVisibility(percentage);
            }
        });

        manager = new GridLayoutManager(this, 1);
        manager.setOrientation(GridLayoutManager.HORIZONTAL);
        moviedatailsRecyclerView.setLayoutManager(manager);

        FullyLinearLayoutManager manager1 = new FullyLinearLayoutManager(this);
        manager1.setOrientation(FullyLinearLayoutManager.VERTICAL);
        moviedetailsRecyclerview.setLayoutManager(manager1);

        //调用presenter
        mPresenter.getData(filmID);
        mPresenter.getComment(filmID);

    }


    // 处理ToolBar的显示
    private void handleToolbarTitleVisibility(float percentage) {
        if (percentage >= PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR) {
            if (!mIsTheTitleVisible) {
                startAlphaAnimation(moviedetailsToolbar, ALPHA_ANIMATIONS_DURATION, View.VISIBLE);
                mIsTheTitleVisible = true;
                //  moviedetailsToolbar.setVisibility(View.VISIBLE);
            }
        } else {
            if (mIsTheTitleVisible) {
                startAlphaAnimation(moviedetailsToolbar, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE);
                mIsTheTitleVisible = false;
                //   moviedetailsToolbar.setVisibility(View.INVISIBLE);
            }
        }
    }


    // 设置渐变的动画
    public static void startAlphaAnimation(View v, long duration, int visibility) {
        AlphaAnimation alphaAnimation = (visibility == View.VISIBLE)
                ? new AlphaAnimation(0f, 100f)
                : new AlphaAnimation(100f, 0f);

        alphaAnimation.setDuration(4);
        alphaAnimation.setFillAfter(true);
        v.startAnimation(alphaAnimation);
    }


    @Override
    public void getData(final Details details) {
        //电影名
        moviedatailsTvmovie.setText(details.getData().get(0).getFilmName());
        //英文电影名
        moviedatailsMovieEnglish.setText(details.getData().get(0).getEnglishName());
        //类型
        moviedatailsMovieType.setText(details.getData().get(0).getFilmType());
        //时长
        moviedatailsMovieTime.setText(details.getData().get(0).getLength());
        //地区
        moviedatailsMovieAddress.setText(details.getData().get(0).getNation());
        //评分
        moviedetailsGrade.setText(details.getData().get(0).getGrade());
        //影片介绍
        moviedatailsMovieRecommend.setText(details.getData().get(0).getSynopsis());
        //背景图片
        Glide.with(this).load(details.getData().get(0).getBigPoster()).into(moviedatailsMovieBackground);
        //演员名单
        Log.i("tag","--------------->"+details.getData().get(0).getActorInfo().get(0).getActorName());
        MovieDetailsAdapter adapter = new MovieDetailsAdapter(details.getData().get(0).getActorInfo(), this);
        moviedatailsRecyclerView.setAdapter(adapter);
        //适配影讯
//        if (details.getData().get(0).getFilmInfos().size() >0) {
       //     Toast.makeText(this,"----"+details.getData().get(0).getFilmInfos().size(),Toast.LENGTH_SHORT).show();
            re.setVisibility(View.VISIBLE);
            MovieDetailsViewPagerAdapter pagerAdapter = new MovieDetailsViewPagerAdapter(getApplicationContext(), details.getData().get(0).getFilmInfos());
            moviedetailsViewpager.setAdapter(pagerAdapter);

            //初始化viewpager上的小圆点
            icons = new ImageView[details.getData().get(0).getFilmInfos().size()];
            List<ImageView> imageViewslist = new ArrayList<>();
            for (int i = 0; i < icons.length; i++) {
                ImageView iv = new ImageView(getApplicationContext());
                iv.setPadding(7, 0, 7, 0);
                imageViewslist.add(iv);
                moviedetailsLinear.addView(iv);
                iv.setImageResource(R.drawable.iv_feature_point);
                icons[i] = iv;

                icons[i].setImageResource(R.drawable.iv_feature_point);
            }
            icons[0].setImageResource(R.drawable.iv_feature_point_cur);
            moviedetailsArticleTitle.setText(details.getData().get(0).getFilmInfos().get(0).getArticleTitle());
            //viewpage滚动监听
            ScrollLinstenter(details);
//        } else {
//            re.setVisibility(View.GONE);
//        }


    }

    //滚动监听  指示图标跟随动 文字跟随动
    private void ScrollLinstenter(final Details details) {
        moviedetailsViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < icons.length; i++) {
                    icons[i].setImageResource(R.drawable.iv_feature_point);
                }

                icons[position].setImageResource(R.drawable.iv_feature_point_cur);
                moviedetailsArticleTitle.setText(details.getData().get(0).getFilmInfos().get(position).getArticleTitle());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void getFail(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    //评论回传成功
    @Override
    public void onComment(final Comment comment) {
        Log.i("----", "1111111111" + comment.getData().get(0).getAuthorName());
        MoviedetailsRecyAdapter adapter = new MoviedetailsRecyAdapter(getApplicationContext(), comment.getData(), new MoviedetailsRecyAdapter.moviedetailsRecyListen() {
            @Override
            public void onclick(int position, View v) {
                //跳转到消息详情界面
                Intent intent = new Intent(getApplicationContext(), MoviesCommentActivity.class);
                intent.putExtra("reviewId", comment.getData().get(position).getReviewId());

                Bundle bundle = new Bundle();
                bundle.putString("reviewId", comment.getData().get(position).getReviewId());
                bundle.putString("username", comment.getData().get(position).getAuthorName());
                bundle.putString("commend", comment.getData().get(position).getReviewContent());
                bundle.putString("commenduserPci", comment.getData().get(position).getAuthorHeadPic());
                bundle.putString("commend_commendNum", comment.getData().get(position).getCommentCounts());
                bundle.putString("commend_goodNum", comment.getData().get(position).getLikeCount());

                Date date = new Date(Long.valueOf(comment.getData().get(position).getReviewTime()) * 1000);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String str = format.format(date);
                bundle.putString("commendtime", str);


                intent.putExtras(bundle);

                startActivity(intent);

            }
        });
        moviedetailsRecyclerview.setAdapter(adapter);
    }

    //消息回传失败
    @Override
    public void onCommentFail(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    //单击事件
    @OnClick({R.id.moviedtails_back, R.id.moviedetails_play, R.id.moviedatails_still, R.id.movieback, R.id.stills, R.id.movieplay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.moviedtails_back:
            case R.id.movieback:
                // Toast.makeText(this, "houtui", Toast.LENGTH_SHORT).show();
                this.finish();
                break;
            case R.id.moviedetails_play:
            case R.id.movieplay:

                Toast.makeText(this, "bofang", Toast.LENGTH_SHORT).show();
                break;
            case R.id.moviedatails_still:
            case R.id.stills:


                break;
        }
    }
}

